package br.com.lucasddaniel.inbuzios.activities;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URI;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import br.com.lucasddaniel.inbuzios.Controller;
import br.com.lucasddaniel.inbuzios.R;
import br.com.lucasddaniel.inbuzios.dao.ExcessaoBanco;
import br.com.lucasddaniel.inbuzios.util.CachedFileProvider;

public class ConfiguracoesActivity extends Activity implements OnClickListener {

	private final String ERRO = "Erro";
	private final String ALERTA = "Alerta";
	private final Handler mHandler = new Handler();

	private ImageView imgImportarDados;
	private ImageView imgImprimir;
	private ImageView imgExportarDados;
	private ImageView imgConfigRelatorio;
	private boolean showMenu;
	private File cacheFilePasseios;
	private File cacheFileTuristas;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_configuracoes);
		Intent i = getIntent();
		if (i.getExtras() != null) {
			showMenu = i.getBooleanExtra("showMenu", false);
		}
		initializeComponents();
	}

	private void sendMail() {
//		Intent emailIntent = new Intent(Intent.ACTION_SEND);
		Intent emailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
		emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Exportação " + new Date());
		emailIntent.putExtra(Intent.EXTRA_TEXT, "Segue anexo os arquivos de exportação .txt com os dados...");
		if (Controller.isVersaoproducao()) {
			emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "luis.suruagy@gmail.com" });
		} else {
			emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "lucasddaniel@gmail.com" });
		}
		emailIntent.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail");
		emailIntent.setType("plain/text");
//		try {
//			createCachedFile(this, arq, new File(arq).toString());
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
		ArrayList<Uri> uris = new ArrayList<Uri>();
		uris.add(Uri.parse("content://" + CachedFileProvider.AUTHORITY + "/" + cacheFilePasseios.getName()));
		uris.add(Uri.parse("content://" + CachedFileProvider.AUTHORITY + "/" + cacheFileTuristas.getName()));
		emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
//		if (cacheFilePasseios != null) {
//			emailIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse("content://" + CachedFileProvider.AUTHORITY + "/" + cacheFilePasseios.getName()));
//		}
//		if (cacheFileTuristas != null) {
//			emailIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse("content://" + CachedFileProvider.AUTHORITY + "/" + cacheFileTuristas.getName()));
//		}
		startActivity(emailIntent);
	}

	public void createCachedFilePasseios(String content) throws IOException {
		Calendar c = Calendar.getInstance();
		cacheFilePasseios = new File(ConfiguracoesActivity.this.getCacheDir() + File.separator + "passeios" + c.get(Calendar.DAY_OF_MONTH) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + 
				c.get(Calendar.YEAR) + "_" + c.get(Calendar.HOUR_OF_DAY) + "-" + c.get(Calendar.MINUTE) + "-" + c.get(Calendar.SECOND) + ".txt");
		cacheFilePasseios.createNewFile();
		FileOutputStream fos = new FileOutputStream(cacheFilePasseios);
		OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF8");
		PrintWriter pw = new PrintWriter(osw);
		pw.println(content);
		pw.flush();
		pw.close();
	}
	
	public void createCachedFileTuristas(String content) throws IOException {
		Calendar c = Calendar.getInstance();
		cacheFileTuristas = new File(ConfiguracoesActivity.this.getCacheDir() + File.separator + "turistas" + c.get(Calendar.DAY_OF_MONTH) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + 
				c.get(Calendar.YEAR) + "_" + c.get(Calendar.HOUR_OF_DAY) + "-" + c.get(Calendar.MINUTE) + "-" + c.get(Calendar.SECOND) + ".txt");
		cacheFileTuristas.createNewFile();
		FileOutputStream fos = new FileOutputStream(cacheFileTuristas);
		OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF8");
		PrintWriter pw = new PrintWriter(osw);
		pw.println(content);
		pw.flush();
		pw.close();
	}
	
	private void initializeComponents() {
		imgExportarDados = (ImageView) findViewById(R.id_activity_menu.img_exportardados);
		imgImportarDados = (ImageView) findViewById(R.id_activity_menu.img_importardados);
		imgImprimir = (ImageView) findViewById(R.id_activity_menu.img_impressao);
		imgConfigRelatorio = (ImageView) findViewById(R.id_activity_menu.img_conf_relat);
		imgExportarDados.setOnClickListener(this);
		imgImportarDados.setOnClickListener(this);
		imgImprimir.setOnClickListener(this);
		imgConfigRelatorio.setOnClickListener(this);
	}

	public void onClick(View view) {
		switch (view.getId()) {
		case R.id_activity_menu.img_exportardados:
			AsyncTask<Void, Void, Void> asExp = new AsyncTask<Void, Void, Void>() {
				ProgressDialog dialog;
				Context ctx = getApplication().getApplicationContext();
				
				@Override
				protected void onPreExecute() {
					super.onPreExecute();
					dialog = new ProgressDialog(ConfiguracoesActivity.this);
					dialog.setCancelable(false);
					dialog.setMessage("Aguarde...");
					dialog.show();
				}

				@Override
				protected Void doInBackground(Void... params) {
					try {
						createCachedFileTuristas(Controller.getInstance().exportarDadosTuristas(ctx));
						createCachedFilePasseios(Controller.getInstance().exportarDadosPasseios(ctx));
//						arquivo = Controller.getInstance().exportarDados(ctx);
					} catch (FileNotFoundException e) {
						Log.e(ALERTA, e.getMessage());
					} catch (IOException e) {
						Log.e(ERRO, e.getMessage());
					} catch (ExcessaoBanco e) {
						Log.e(ERRO, e.getMessage());
					}
					return null;
				}

				@Override
				protected void onPostExecute(Void retorno) {
					super.onPostExecute(retorno);
					dialog.cancel();
					dialog.dismiss();
					AsyncTask<Void, Void, Void> asExp = new AsyncTask<Void, Void, Void>() {

						ProgressDialog dialog;

						@Override
						protected void onPreExecute() {
							super.onPreExecute();
							dialog = new ProgressDialog(ConfiguracoesActivity.this);
							dialog.setCancelable(false);
							dialog.setMessage("Aguarde...");
							dialog.show();
						}

						@Override
						protected Void doInBackground(Void... params) {
							sendMail();
							return null;
						}

						@Override
						protected void onPostExecute(Void retorno) {
							super.onPostExecute(retorno);
							dialog.cancel();
							dialog.dismiss();
						}
					};
					asExp.execute((Void)null);
				}
			};
			asExp.execute((Void)null);
			break;
		case R.id_activity_menu.img_turistas:
			startActivity(new Intent(this, ListarTuristasActivity.class));
			break;
		case R.id_activity_menu.img_pacotes:
			startActivity(new Intent(this, ListarPacotesActivity.class));
			break;
		case R.id_activity_menu.img_importardados:
			AsyncTask<Void, Void, Void> asImp = new AsyncTask<Void, Void, Void>() {
				ProgressDialog dialog;

				@Override
				protected void onPreExecute() {
					super.onPreExecute();
					dialog = new ProgressDialog(ConfiguracoesActivity.this);
					dialog.setCancelable(false);
					dialog.setMessage("Aguarde...");
					dialog.show();
				}

				@Override
				protected Void doInBackground(Void... params) {
					boolean sucesso = false;
					try {
						sucesso = Controller.getInstance().importarDados(
								getApplicationContext());
					} catch (FileNotFoundException e) {
						notificarUsuario("", e.getMessage());
					} catch (IOException e) {
						notificarUsuario(ERRO, e.getMessage());
					} catch (ExcessaoBanco e) {
						notificarUsuario(ERRO, e.getMessage());
					} finally {
						if (sucesso) {
							notificarUsuario("",
									"Dados importados com sucesso.");
						}
					}
					return null;
				}

				@Override
				protected void onPostExecute(Void retorno) {
					super.onPostExecute(retorno);
					dialog.cancel();
					dialog.dismiss();
				}
			};
			asImp.execute((Void)null);
			break;
		case R.id_activity_menu.img_cadastro:
			Intent i = new Intent(this, TuristasActivity.class);
			i.putExtra("fromMenu", true);
			startActivity(i);
			break;
		case R.id_activity_menu.img_conf_relat:
			 AlertDialog dialog3 = new AlertDialog.Builder(this).create();
             dialog3.setMessage("É obrigatório que a impressora seja ligada nesse momento");
             dialog3.setButton("OK", new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog3, int whichButton) {
                     dialog3.dismiss();
                     startActivity(new Intent(ConfiguracoesActivity.this, RelatoriosActivity.class));
                 }
             });
             dialog3.show();
			break;
		case R.id_activity_menu.img_impressao:
			startActivity(new Intent(this, EscaneamentoActivity.class));
			break;
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		//cacheFile.delete();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}

	/**
	 * Exibe uma mensagem ao usuario de acordo com os parametros passados. Usada
	 * em excessoes.
	 * 
	 * @param titulo
	 * @param message
	 */
	protected void notificarUsuario(final String titulo, final String message) {
		mHandler.post(new Runnable() {
			public void run() {
				new AlertDialog.Builder(ConfiguracoesActivity.this).setTitle(titulo)
						.setMessage(message).create().show();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (showMenu) {
			menu.add(Menu.NONE, Menu.FIRST, Menu.NONE, getResources()
					.getString(R.string.menu_label_custom));
		}
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == Menu.FIRST) {
			Intent intent = new Intent(this, CadastroResponsavelActivity.class);
			this.startActivity(intent);
		}

		return super.onOptionsItemSelected(item);
	}
}
